//
//  CZEmoticonTools.swift
//  weiBo
//
//  Created by apple on 16/5/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZEmoticonTools: NSObject  {

    //设置单例
    static let sharedTools: CZEmoticonTools = CZEmoticonTools()
    
    override init() {
        super.init()
        
    }
    
    //获取bundle对象
    private lazy var emoticonBunle: NSBundle = {
        //获取地址
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        //创建bundle对象
        let bundle = NSBundle(path: path)!
        
        return bundle
    }()
    
    //字典转模型
    //  读取默认表情
    private lazy var defaultEmoticons: [CZEmoticon] = {
        return self.loadEmoticonsWithPath("default/info.plist")
    }()
    
    //  读取emoji表情
    private lazy var emojiEmoticons: [CZEmoticon] = {
        return self.loadEmoticonsWithPath("emoji/info.plist")
    }()
    
    //  浪小花
    private lazy var lxhEmoticons: [CZEmoticon] = {
        return self.loadEmoticonsWithPath("lxh/info.plist")
    }()
    
    lazy var allEmoticons: [[[CZEmoticon]]] = {
        return [
            self.sectionWithEmotions(self.defaultEmoticons),
            self.sectionWithEmotions(self.emojiEmoticons),
            self.sectionWithEmotions(self.lxhEmoticons)
        ]
    }()
    
    
    //抽取字典转模型的方法
    private func loadEmoticonsWithPath(subPath: String) -> [CZEmoticon] {
        let path = self.emoticonBunle.pathForResource(subPath, ofType: nil)
        //加载数据
        let array = NSArray(contentsOfFile: path!)!
        //创建可变的模型数组
        var tempArray = [CZEmoticon]()
        //遍历数组
        for dic in array {
            let emotion = CZEmoticon(dic: dic as! [String : AnyObject])
            //  判断是否是图片
            if emotion.type == "0" {
                
                let png = emotion.png!
                //  把路径里面的最后一部分干掉
                let subPath = (path! as NSString).stringByDeletingLastPathComponent
                //  图片的全路径
                emotion.path = subPath + "/" + png
            }

            tempArray.append(emotion)
        }
        
        return tempArray
    }
    
    //拆分模型数组  转为模型二维数组
    private func sectionWithEmotions(emoticons: [CZEmoticon]) -> ([[CZEmoticon]]) {
        //计算页数
        let pageCount = (emoticons.count - 1) / 20 + 1
        //定义可变模型数组
        var nmArray: [[CZEmoticon]] = [[CZEmoticon]]()
        //遍历模型数组
        for i in 0..<pageCount {
            let locaction = i * 20
            var length = 20
            
            if locaction + length > emoticons.count {
                length = emoticons.count - locaction
            }
            
           let subArray = (emoticons as NSArray).subarrayWithRange(NSMakeRange(locaction, length)) as! [CZEmoticon]
            nmArray.append(subArray)
        }
    
    
        return nmArray
    }
    
    
    
    
}
